import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import { getWxTicket, getAgentTicket } from '@/api/common'
import store from '@/store'
import { Toast } from 'vant'
import { getWxCode, getQueryValue } from '@/utils/index'

Vue.use(VueRouter)
let noAuth = true // 设置页面是否关闭授权登录鉴权，用于开发静态页面统一配置

/**
 * 路由字段说明
 * meta:{
 *   title: 页面标题
 *   noAuth: 设置页面是否关闭授权登录鉴权，用于本地开发静态页面调试和某些不要登录的页面
 *   authType: 登录类型： 企微登录（默认），wechat(微信登录)
 *   wxSDKConfigType:  wx JS SDK config类型; 取值: 无值默认(企微端), wechat(微信端), no(不调用sdk config配置)
 * }
 */
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    redirect: process.env.NODE_ENV === 'development' ? '' : '/index',
    meta: {
      title: window.lwConfig.SYSTEM_NAME,
      noAuth: true,
    },
  },
  // 首页
  {
    path: '/index',
    component: () => import('../views/index/Parent'),
    meta: {
      title: window.lwConfig.SYSTEM_NAME,
      noAuth:true,
    },
    children: [
      {
        path: '/index',
        name: 'index',
        component: () => import('../views/index/index.vue'),
        meta: {
          title: '首页',
          noAuth: true,
          icon: 'home-o',
        },
      },
      {
        path: 'customer',
        name: 'customer',
        component: () => import('../views/index/customer'),
        meta: {
          title: '客户',
          noAuth,
          icon: 'user-o',
        },
      },
      {
        path: 'customerGroup',
        name: 'customerGroup',
        component: () => import('../views/index/customerGroup'),
        meta: {
          title: '客群',
          noAuth,
          icon: 'friends-o',
        },
      },
      {
        path: 'apps',
        name: 'apps',
        component: () => import('../views/index/apps'),
        meta: {
          title: '应用',
          noAuth,
          icon: 'apps-o',
        },
      },
    ],
  },
  //   企业动态
  {
    path: '/dynamics',
    name: 'dynamics',
    component: () => import('../views/index/dynamics'),
    meta: {
      title: '企业动态',
      noAuth,
    },
  },

  //客户SOP 工作台
  {
    path: '/personalSOPDetails',
    name: 'personalSOPDetails',
    component: () => import('../views/Applications/customerManagement/personalSOPDetails'),
    meta: {
      title: '客户SOP',
      noAuth,
    },
  },
  //客群SOP 工作台
  {
    path: '/customerBaseDetails',
    name: 'customerBaseDetails',
    component: () => import('../views/Applications/customerBase/customerBaseDetails'),
    meta: {
      title: '客群SOP',
      noAuth,
    },
  },

  //侧边栏个人SOP
  {
    path: '/sop',
    name: 'sop',
    component: () => import('../views/Applications/communityOperations/index'),
    meta: {
      title: '客户/客群SOP',
      noAuth,
    },
  },

  // 红包卡券拉新页面
  {
    path: '/pullNews',
    name: 'pullNews',
    component: () => import('../views/pullNews/pullNews'),
    meta: {
      title: '新客红包',
      noAuth: true,
    },
  },
  //   企业动态
  {
    path: '/dynamics',
    name: 'dynamics',
    component: () => import('../views/index/dynamics'),
    meta: {
      title: '企业动态',
      noAuth,
    },
  },
  // 流失客户
  {
    path: '/lostCustomers',
    name: 'lostCustomers',
    component: () => import('../views/index/lostCustomers'),
    meta: {
      title: '流失客户',
      noAuth,
    },
  },

  // 聊天素材
  {
    path: '/chat',
    name: 'chat',
    component: () => import('../views/chat'),
    meta: {
      title: '聊天素材',
      noAuth,
    },
  },
  // 素材预览，详情
  {
    path: '/metrialDetail',
    name: 'metrialDetail',
    component: () => import('../views/chat/detail'),
    meta: {
      title: '素材详情',
      noAuth: true,
    },
  },

  // 企业话术
  {
    path: '/enterpriseChat',
    name: 'enterpriseChat',
    component: () => import('../views/talkCenter/enterpriseChat'),
    meta: {
      title: '企业话术',
      noAuth,
    },
  },
  // 客服话术
  {
    path: '/customerChat',
    name: 'customerChat',
    component: () => import('../views/talkCenter/customerChat'),
    meta: {
      title: '客服话术',
      noAuth,
    },
  },

  // 用户画像
  {
    path: '/portrait',
    name: 'portrait',
    component: () => import('../views/portrait/index'),
    meta: {
      title: '客户画像',
      noAuth,
    },
  },
  //  用户画像-新增订单
  {
    path: '/portraitAdd',
    name: 'portraitAdd',
    component: () => import('../views/portrait/addOrder.vue'),
    hidden: true,
    meta: {
      title: '新增订单',
      noAuth,
    },
  },

  // 开播提醒页
  {
    path: '/reminder',
    name: 'reminder',
    component: () => import('../views/reminder/index'),
    meta: {
      title: window.lwConfig.SYSTEM_NAME,
      noAuth: true,
    },
  },
  //  用户画像-详情
  // {
  //   path: '/customerDetail',
  //   name: 'customerDetail',
  //   component: () => import('../views/portrait/customerDetail.vue'),
  //   hidden: true,
  //   meta: {
  //     title: '',
  //     noAuth,
  //   },
  // },
  // 用户画像-社群关系
  {
    path: '/community',
    name: 'community',
    component: () => import('../views/portrait/community.vue'),
    hidden: true,
    meta: {
      title: '社群关系',
      noAuth,
    },
  },
  // 客群画像
  {
    path: '/portraitGroup',
    name: 'portraitGroup',
    component: () => import('../views/portraitGroup/index.vue'),
    hidden: true,
    meta: {
      title: '客群画像',
      noAuth,
    },
  },
  {
    path: '/groupMembers',
    name: 'groupMembers',
    component: () => import('../views/portraitGroup/members.vue'),
    hidden: true,
    meta: {
      title: '群成员',
      noAuth,
    },
  },
  // 群活码扫描跳转页面
  {
    path: '/groupCode',
    name: 'groupCode',
    component: () => import('../views/groupCode/index'),
    hidden: true,
    meta: {
      title: '群活码',
      noAuth: true,
    },
  },
  // 标签建群+群sop
  {
    path: '/task',
    hidden: true,
    meta: {
      title: '消息群发',
      noAuth: true,
    },
    component: () => import('../views/communityOperating/task/index'),
    children: [
      {
        path: '',
        component: () => import('../views/communityOperating/task/list'),
        hidden: true,
        meta: {
          title: '消息群发',
          // noAuth: true
        },
      },
      {
        path: 'state',
        name: 'taskState',
        component: () => import('../views/communityOperating/task/state.vue'),
        hidden: true,
        meta: {
          title: '消息群发',
          noAuth: true,
        },
      },
    ],
  },
  // 关键词群
  {
    path: '/keywords',
    name: 'keywords',
    component: () => import('../views/communityOperating/keywords/index'),
    hidden: true,
    meta: {
      title: '关键词群',
      authType: 'wechat',
      wxSDKConfigType: 'no',
    },
  },

  // 红包
  {
    path: '/redPacket',
    name: 'redPacket',
    component: () => import('../views/redPacket/index'),
    meta: {
      title: '红包',
    },
  },
  // 领取红包
  {
    path: '/redPacketReceive',
    name: 'redPacketReceive',
    component: () => import('../views/redPacket/receive'),
    meta: {
      title: '领取红包',
      noAuth: true,
    },
  },
  // 领取卡券
  {
    path: '/redOrCardPullNews',
    name: 'cardPullNews',
    component: () => import('../views/pullNews/cardPullNews'),
    meta: {
      title: '领取红包',
      noAuth: true,
    },
  },
  // 任务宝、群裂变
  {
    path: '/taskTreasure',
    name: 'taskTreasure',
    component: () => import('../views/task/index'),
    meta: {
      title: '裂变任务',
      noAuth: true,
    },
  },
  // 任务宝、群裂变 任务进度查询
  {
    path: '/taskProcess',
    name: 'taskProcess',
    component: () => import('../views/task/process'),
    meta: {
      title: '任务进度',
      noAuth: true,
    },
  },
  // 群裂变 扫码结果页面
  {
    path: '/fission',
    name: 'fission',
    component: () => import('../views/fission/index'),
    meta: {
      title: '群裂变',
      noAuth: true,
    },
  },
  // 门店活码
  {
    path: '/guideCode',
    name: 'guideCode',
    component: () => import('../views/storeCode/index'),
    hidden: true,
    meta: {
      title: '门店导购码',
      noAuth: true,
    },
  },
  {
    path: '/storeCode',
    name: 'storeCode',
    component: () => import('../views/storeCode/code'),
    hidden: true,
    meta: {
      title: '门店群活码',
      noAuth: true,
    },
  },
  {
    path: '/evaluate',
    name: 'evaluate',
    component: () => import('../views/evaluate/evaluate'),
    meta: {
      title: '会话服务评价',
      noAuth: true,
    },
  },
  {
    path: '/identity',
    name: 'identity',
    component: () => import('../views/identity/identity'),
    meta: {
      title: '识客活码',
      noAuth: true,
    },
  },
  // 短链推广 应用消息H5
  {
    path: '/shortLinkPush',
    name: 'shortLinkPush',
    component: () => import('../views/shortLinkPush/index'),
    meta: {
      title: '短链推广',
    },
  },
  // 会话质检 成员记录
  {
    path: '/quality',
    name: 'quality',
    component: () => import('../views/quality/quality'),
    meta: {
      title: '会话质检',
      // noAuth: true
    },
  },
  // 朋友圈营销
  {
    path: '/friends',
    name: 'friends',
    component: () => import('../views/friends/index'),
    meta: {
      title: '朋友圈营销',
      // noAuth: true,
    },
  },
  {
    path: '/friendsDetail',
    name: 'friendsDetail',
    component: () => import('../views/friends/detail'),
    meta: {
      title: '营销详情',
      // noAuth: true,
    },
  },
  {
    path: '/weekly',
    name: 'weekly',
    component: () => import('../views/quality/weekly'),
    meta: {
      title: '周报',
      // noAuth: true
    },
  },
  {
    path: '/weekly-detail',
    name: 'weekly-detail',
    component: () => import('../views/quality/detail'),
    meta: {
      title: '成员质检详情',
      // noAuth: true
    },
  },

  // 消息通知
  {
    path: '/message',
    component: () => import('../views/message/index'),
    meta: {
      title: '消息通知',
      noAuth: true,
    },
  },

  // 历史任务
  {
    path: '/historyTask',
    name: 'historyTask',
    component: () => import('../views/myTask/history'),
    meta: {
      title: '历史任务',
    },
  },

  // 老客迁移 （旧的客户公海）
  // {
  //   path: '/highSeas',
  //   name: 'highSeas',
  //   component: () => import('../views/highSeas/index'),
  //   meta: {
  //     title: '老客迁移',
  //   },
  // },

  // 线索公海
  {
    path: '/clueHighseas/index',
    name: 'clueHighseas',
    component: () => import('../views/clueHighseas/index/index'),
    meta: {
      title: '线索公海',
    },
  },
  // 线索详情
  {
    path: '/clueHighseas/detail',
    name: 'clueDetail',
    component: () => import('../views/clueHighseas/detail'),
    meta: {
      title: '线索详情',
      // noAuth,
    },
  },
  // 跟进详情
  {
    path: '/clueHighseas/followDetail',
    name: 'followDetail',
    component: () => import('../views/clueHighseas/followDetail'),
    meta: {
      title: '跟进详情',
      // noAuth,
    },
  },

  // // 编辑详情
  // {
  //   path: '/highSeas/detail/edit',
  //   name: 'clueDetailEdit',
  //   component: () => import('../views/clueHighseas/edit'),
  //   meta: {
  //     title: '编辑详情',
  //     noAuth,
  //   },
  // },
  // // 添加跟进
  // {
  //   path: '/highSeas/detail/followup',
  //   name: 'clueFollowup',
  //   component: () => import('../views/clueHighseas/followup'),
  //   meta: {
  //     title: '添加跟进',
  //     noAuth,
  //   },
  // },
  // // 线索退回
  // {
  //   path: '/highSeas/detail/back',
  //   name: 'clueBack',
  //   component: () => import('../views/clueHighseas/back'),
  //   meta: {
  //     title: '线索退回',
  //     noAuth,
  //   },
  // },
  // // 线索转移
  // {
  //   path: '/highSeas/detail/transfer',
  //   name: 'clueTransfer',
  //   component: () => import('../views/clueHighseas/transfer'),
  //   meta: {
  //     title: '线索转移',
  //     noAuth,
  //   },
  // },

  // 咨询线索
  {
    path: '/clueHighseas/consult',
    name: 'consultClue',
    component: () => import('../views/clueHighseas/consult'),
    meta: {
      title: '咨询线索',
      // noAuth,
    },
  },

  // 解决授权重定向返回问题
  { path: '*', redirect: '/', hidden: true },
]

const router = new VueRouter({
  // mode: 'history', window.lwConfig
  base: window.lwConfig.BASE_URL,
  routes,
})

router.beforeEach(async (to, from, next) => {
  Toast.clear()
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  // 通过config接口注入权限验证配置
  // 所有需要使用JS-SDK的页面必须先注入配置信息，否则将无法调用（同一个url仅需调用一次，对于变化url的SPA（single-page application）的web app可在每次url变化时进行调用）
  try {
    if (!sessionStorage.token && !to.meta?.noAuth) {
      Toast.loading()
      await (to.meta?.authType === 'wechat' ? getWxCode() : store.dispatch('login'))
      process.env.NODE_ENV !== 'development' && to.meta?.wxSDKConfigType !== 'no' && (await wxConfig(to.meta?.authType))
      Toast.clear()
    }
    next()

    // if (noAuth) {
    //   next()
    // } else {
    //   getQueryValue('code') && next()
    // }
  } catch (error) {
    // error && alert(JSON.stringify(error))
    Toast.clear()
    next(false)
  }
})

function wxConfig(type) {
  try {
    return new Promise((resolve, reject) => {
      if (type === 'wechat') {
        getWxTicket(window.location.href.split('#')[0]).then(({ data }) => {
          let { timestamp, nonceStr, signature } = data
          wx.config({
            beta: true,
            debug: true,
            appId: sessionStorage.getItem('weAppId'),
            timestamp, // 必填，生成签名的时间戳
            nonceStr, // 必填，生成签名的随机串
            signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
            jsApiList: ['getLocation', 'chooseImage', 'previewImage'], //必填
            openTagList: ['wx-open-launch-weapp'],
            success: (res) => {
              resolve()
            },
            fail: (res) => {
              alert('config失败:' + JSON.stringify(res))
              if (res.errMsg.indexOf('function not exist') > -1) {
                alert('版本过低请升级')
              }
              reject()
            },
          })
        })
      } else {
        getAgentTicket(window.location.href.split('#')[0]).then(({ data }) => {
          let { timestamp, nonceStr, signature } = data
          setTimeout(() => {
            wx.agentConfig({
              beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
              debug: true,
              corpid: sessionStorage.corpId, // 必填，企业微信的corpid，必须与当前登录的企业一致
              agentid: sessionStorage.agentId, // 必填，企业微信的应用id （e.g. 1000247）
              timestamp, // 必填，生成签名的时间戳
              nonceStr, // 必填，生成签名的随机串
              signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
              jsApiList: [
                'sendChatMessage',
                'getContext',
                'getCurExternalContact',
                'getCurExternalChat',
                'openEnterpriseChat',
                'shareToExternalContact',
                'shareToExternalChat',
                'navigateToAddCustomer',
                'openEnterpriseChat',
                'openExistedChatWithMsg',
                'shareToExternalMoments',
              ], //必填
              success: (res) => {
                // 回调
                // toast('agentId成功:')
                resolve()
              },
              fail: (res) => {
                alert('agent config失败:' + JSON.stringify(res))
                if (res.errMsg.indexOf('function not exist') > -1) {
                  alert('版本过低请升级')
                }
                reject()
              },
            })
          }, 20)
        })
      }
    })
  } catch (error) {
    error && alert(JSON.stringify(error))
    return Promise.reject()
  }
}

export default router
